/**
 * 作者: hxl
 * 日期: 2024-10-16 15:05:41
 * 备注: 秘书
 */
package com.motu.monstercity.server.game.userdata;

import com.motu.monstercity.module.common.utility.Constant;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.protocol.Common.PBUserSecretary;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.rank.RankConstant;
import com.motu.monstercity.server.game.commondata.secretary.SecretaryMain;
import com.motu.monstercity.server.game.commondata.secretary.SecretaryPotentialSkill;
import com.motu.monstercity.server.game.commondata.skill.Skill;
import com.motu.monstercity.server.game.log.MotuLogManager;
import com.motu.monstercity.server.game.logic.*;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import io.vertx.core.json.JsonArray;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class UserSecretary extends UserSecretaryModel {
    public UserSecretary() {
        super();
    }
    public UserSecretary(PBUserData.Builder pbUserData, UserInfo userInfo, UserPower userPower, SecretaryMain secretaryMain) {
        putUserId(userInfo.getId());
        putSecretaryId(secretaryMain.getSecretaryId());
        putEnergy(AllParam.SECRETRAY_MAX_ENERGY_VALUE);
        putRecoverEnergyTime(TimeUtils.getCurTime());
        putIdentitySkillLevel(pbUserData, userInfo, userPower, secretaryMain.getIdentity());
        initSkillLevelData();
        putBusinessValue(SkillManager.createSkillEffectArray().toString());//[0,0,0,0,0,0]
    }

    public void putIdentitySkillLevel(PBUserData.Builder pbUserData, UserInfo userInfo, UserPower userPower, int identitySkillLevel) {
        if (this.identitySkillLevel != identitySkillLevel) {
            int oldLevel = takeIdentitySkillLevel();// 升级之前的基因等级
            super.putIdentitySkillLevel(identitySkillLevel);
            int newLevel = takeIdentitySkillLevel();// 升级之后的基因等级， 不是每次升级都会提升等级
            if (newLevel > oldLevel) {
                SecretaryManager.handleSecrIdentityLevelUp(pbUserData, userInfo, userPower, this, getIdentitySkillId(), newLevel);
            }
        }
    }

    public PBUserSecretary.Builder takeBuilder() {
        PBUserSecretary.Builder sb = super.takeBuilder();
        sb.setIdentity(takeIdentitySkillLevel());
        return sb;
    }

    public PBUserSecretary.Builder takeInitBuilder() {
        PBUserSecretary.Builder sb = super.takeInitBuilder();
        sb.setIdentity(takeIdentitySkillLevel());
        return sb;
    }

    public PBUserSecretary.Builder takeBuilderBusiness(UserSecretaryBusiness userSecretaryBusiness) {
        PBUserSecretary.Builder sb = PBUserSecretary.newBuilder();
        sb.putBusiness(userSecretaryBusiness.getSkillId(), userSecretaryBusiness.takeInitBuilder().build());
        return sb;
    }

    /**
     * 获取实际的基因技能的实际等级，identity_skill_level 这个是升级次数，不一定每次升级都会提示等级
     * @return
     */
    public int takeIdentitySkillLevel() {
        SecretaryMain secretaryMain = SecretaryManager.getSecretaryMain(getSecretaryId());
        if (secretaryMain == null) {
            return 0;
        }
        int[] array = secretaryMain.takeIdentitySkillUpdateArray();// 升级进阶配置情况 0;0;1;0;1;0;1;0;1;0;1 表示等级=3，5品质才有提示
        if (array == null || array.length == 0) {
            return 0;
        }
        int total = 0;
        for (int i=0; i<getIdentitySkillLevel(); i++) {
            if (i < array.length && array[i] == 1) {
                total++;
            }
        }
        return total + 1;// 最少1级
    }


    @Override
    public void reset() {
        boolean isUpdate = initSkillLevelData();
        boolean isUpdate2 = recoverEnergy(TimeUtils.getCurTime());

        if (isUpdate || isUpdate2) {
            update();
        }
    }

    public boolean initSkillLevelData() {
        boolean isUpdate = false;
        int skillPatronNum = AllParam.SECRETRAY_PATRONS_SKILL.length;// 基础技能的个数
        JsonArray jsonArray = getSkillPatronLevelArray();// 升级情况
        if (jsonArray.size() != skillPatronNum) {
            putSkillPatronLevel(SkillManager.formatJsonData(jsonArray, skillPatronNum, 1).toString());
            isUpdate = true;
        }
        return isUpdate;
    }

    public boolean recoverEnergy(long time) {
        if (energy >= AllParam.SECRETRAY_MAX_ENERGY_VALUE) { // 已经达到体力上限则只更新恢复时间
            return false;
        }
        long diffTime = time - recoverEnergyTime;
        if (diffTime < AllParam.SECRETRAY_RESTORE_ENERGY_TIME) { // 还没到体力恢复点就返回
            return false;
        }
        long addCount = diffTime / AllParam.SECRETRAY_RESTORE_ENERGY_TIME;
        addCount = Math.min(addCount, AllParam.SECRETRAY_MAX_ENERGY_VALUE);
        if (addCount + energy >= AllParam.SECRETRAY_MAX_ENERGY_VALUE) { // 超出体力上限则取上限值
            putEnergy(AllParam.SECRETRAY_MAX_ENERGY_VALUE);
            putRecoverEnergyTime(time);
            update();
            return true;
        }
        // 正常加体力，并且将溢出时间返还
        addEnergy((int) addCount);
        diffTime = addCount * AllParam.SECRETRAY_RESTORE_ENERGY_TIME;
        addRecoverEnergyTime(diffTime);
        update();
        return true;
    }

    public void clearUpdateObj() {
        if (null != updateObj && !updateObj.isEmpty()) {
            updateObj.clear();
        }
    }


    // 添加亲密度
    public void addFavorite(PBUserData.Builder pbUserData, UserInfo userInfo, UserPower userPower, UserAffair userAffair,  int value) {
        super.addFavorite(value);
        userAffair.addSecrFaviroteTotal(value);
        if (getFavorite() > userAffair.getSecrFaviroteMax()) {
            userAffair.putSecrFaviroteMax(getFavorite());
            MainTaskManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_147, userAffair.getSecrFaviroteMax());
            RankActManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_147, userAffair.getSecrFaviroteMax());
        }
        userAffair.update();
        SecretaryManager.createSecrBusiness(pbUserData, userInfo, userPower, this);
        MainTaskManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_144, userAffair.getSecrFaviroteTotal());
        RankActManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_144, userAffair.getSecrFaviroteTotal());
        MainTaskManager.updateServerHonor(pbUserData, userInfo, MainTaskConstant.HONOR_TYPE_3, userAffair.getSecrFaviroteTotal());
        RankManager.updateRank(RankConstant.SERVER_RANK_SECR, userInfo.getServerId(), userInfo.getId(), userAffair.getSecrFaviroteTotal(), "0");// 更新战力排行榜
    }

    public void addCharm(PBUserData.Builder pbUserData, UserInfo userInfo, int value) {
        super.addCharm(value);
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_200, value);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_199, value);
    }

    public void addFetters(UserInfo userInfo, int num, Object... params) {
        long balance = getFetters();// 当前余额
        long dbid = 0;
        MotuLogManager.logItemIncome(userInfo, ItemId.PARTNER_EXP, dbid, balance, num, params);
        super.addFetters(num);
    }

    public void subFetters(UserInfo userInfo, int num, Object... params) {
        long balance = getFetters();// 当前余额
        if (balance < num) {
            return;
        }
        long dbid = 0;
        MotuLogManager.logItemConsume(userInfo, ItemId.PARTNER_EXP, dbid, balance, num, params);
        super.addFetters(-num);
    }

    // 生的小孩带的城市收益加成
    public double takeChildAdd() {
        double aa = getFavorite();// 母亲的喜爱值
        double addValue = aa * Constant.THOUSAND / (aa + 20000) / 100 ;// 母亲的加成系数0.74 （母亲魅力值* 10000）/（母亲魅力值 + 20000）
        return addValue;
    }

    /**
     * 获取秘书的技能等级情况，key=技能id，value=等级，包括羁绊技能和基因技能
     * @return
     */
    public ConcurrentHashMap<Integer, Integer> takeSkillMap() {
        ConcurrentHashMap<Integer, Integer> tmp = new ConcurrentHashMap<>();
        SecretaryMain secretaryMain = SecretaryManager.getSecretaryMain(getSecretaryId());
        if (secretaryMain == null) {
            return tmp;
        }
        JsonArray jsonArray = getSkillPatronLevelArray();
        for (int i=0; i<AllParam.SECRETRAY_PATRONS_SKILL.length; i++) {// 羁绊技能
            tmp.put(AllParam.SECRETRAY_PATRONS_SKILL[i], jsonArray.getInteger(i));
        }
        tmp.put(secretaryMain.getIdentitySkill(), takeIdentitySkillLevel());
        return tmp;
    }

    // 基因技能的id
    public int getIdentitySkillId() {
        SecretaryMain secretaryMain = SecretaryManager.getSecretaryMain(getSecretaryId());
        if (secretaryMain == null) {
            return 0;
        } else {
            return secretaryMain.getIdentitySkill();
        }
    }

    // 获取羁绊的干员Id 列表
    public JsonArray takePartnerIds() {
        SecretaryMain secretaryMain = SecretaryManager.getSecretaryMain(getSecretaryId());
        if (secretaryMain == null) {
            return null;
        } else {
            return secretaryMain.getSecretaryRelationList();
        }
    }

    // 羁绊技能的加成值
    public int countPatronSkillAdd(int effectType) {
        int totalAdd = 0;
        int[] skillList = AllParam.SECRETRAY_PATRONS_SKILL;
        JsonArray levelList = getSkillPatronLevelArray();
        for (int i=0; i<skillList.length; i++) {
            int skillId = skillList[i];
            int level = levelList.getInteger(i);
            if (skillId > 0 && level > 0) {
                Skill skill = SkillManager.getSkill(skillId);
                if (skill != null && skill.getEffectType() == effectType) {
                    totalAdd += skill.countTotalAdd(level);
                }
            }
        }
        return totalAdd;
    }

    // 增量经营技能的加成
    public void updateBusinessValue(int charType, int addValue) {
        JsonArray jsonArray = getBusinessValueArray();
        if (jsonArray == null || jsonArray.size() == 0) {
            return;
        }
        int newValue = jsonArray.getInteger(charType) + addValue;
        jsonArray.set(charType, newValue);
        putBusinessValue(jsonArray.toString());
    }

    // 登录时异步重算秘书的经营技能
    public void reCountBusiness(UserInfo userInfo, UserPower userPower) {
        SecretaryManager.createSecrBusiness(null, userInfo, userPower, this);// 补齐经营技能
        reCountBusiness(null);
    }

    public void reCountBusiness(PBUserData.Builder pbUserData) {
        List<UserSecretaryBusiness> list = SecretaryManager.getUserSecretaryBusinessList(getUserId(), getSecretaryId());
        int total1 = 0;
        int total2 = 0;
        int total3 = 0;
        int total4 = 0;
        int total5 = 0;
        for (UserSecretaryBusiness userSecretaryBusiness : list) {
            int skillId = userSecretaryBusiness.getSkillId();
            SecretaryPotentialSkill secretaryPotentialSkill = SecretaryManager.getSecretaryPotentialSkill(skillId);
            if (secretaryPotentialSkill.getCharacterType() == Constant.CHARACTER_TYPE_1) {
                total1 += userSecretaryBusiness.getValue();
            } else if (secretaryPotentialSkill.getCharacterType() == Constant.CHARACTER_TYPE_2) {
                total2 += userSecretaryBusiness.getValue();
            } else if (secretaryPotentialSkill.getCharacterType() == Constant.CHARACTER_TYPE_3) {
                total3 += userSecretaryBusiness.getValue();
            } else if (secretaryPotentialSkill.getCharacterType() == Constant.CHARACTER_TYPE_4) {
                total4 += userSecretaryBusiness.getValue();
            } else if (secretaryPotentialSkill.getCharacterType() == Constant.CHARACTER_TYPE_5) {
                total5 += userSecretaryBusiness.getValue();
            }
            ProtoDataUtils.updatePBUserData(pbUserData, userSecretaryBusiness);
        }

        JsonArray jsonArray = new JsonArray();
        jsonArray.add(0);
        jsonArray.add(total1);
        jsonArray.add(total2);
        jsonArray.add(total3);
        jsonArray.add(total4);
        jsonArray.add(total5);
        putBusinessValue(jsonArray.toString());
    }


    // 根据effectType 统计基因技能总的加成值有多少 charType 是作用对像的性格
    public int initCountIdenSkill(int effectType, int charType) {
        int[] skillList =  new int[1];
        skillList[0] = getIdentitySkillId();// 秘书的基因技能
        JsonArray levelList = new JsonArray().add(takeIdentitySkillLevel());
        return SkillManager.initCountSkillValue(skillList, levelList, effectType, charType);
    }
}
